<template>
  <div class="user-list-container">
    <div class="card-header">
      <h2 style="margin: 0; font-size: 20px;">管理用户</h2>
    </div>

    <!-- 搜索和添加区域 -->
    <div class="search-add-area" style="margin-bottom: 20px;">
      <el-input v-model="searchUsername" placeholder="用户名" style="width: 200px; margin-right: 10px;" clearable>
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" :loading="isLoading" @click="GetUserData()" :disabled="isLoading">
        <el-icon v-if="isLoading"><Loading /></el-icon>
        <el-icon v-else><Search /></el-icon>
        查询
      </el-button>
      <el-button type="success" @click="handleAddUser" :disabled="isLoading">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
    </div>
    <!-- 用户数据表格 -->
    <el-table :data="userData" style="width: 100%">
        <el-table-column prop="Id" label="用户编号" width="80" align="center" />
        <el-table-column prop="UserName" label="用户名" width="120" align="center" />
        <el-table-column prop="UserPwd" label="密码" width="120" align="center" />
        <el-table-column prop="RoleName" label="角色" width="240" align="center" />
        <el-table-column prop="IsUse" label="是否启用" width="100" align="center">
            <template v-slot="scope">
                <el-tag type="success" v-if="scope.row.IsUse == true">启用</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="CreateTime" label="创建时间" width="160" align="center">
            <template v-slot="scope">
                {{ moment(scope.row.CreateTime).format("yyyy年MM月DD日HH:MM:ss") }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
            <template v-slot="scope">
                <el-button type="primary" size="small" @click="GetoneUser(scope.row)" :disabled="isLoading">
                    <el-icon><Edit /></el-icon>
                    编辑
                </el-button>
                <el-popconfirm
                  title="确定要删除该用户吗？"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="handleDeleteUser(scope.row.Id)"
                >
                  <template #reference>
                    <el-button type="danger" size="small" :disabled="isLoading">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <!-- 用户新增 -->
    <el-dialog v-model="OpenUserAdd" title="用户新增" width="500" align="center">
        <el-form :model="UserData" label-width="auto" style="max-width: 600px">
            <el-form-item label="用户名">
                <el-input v-model="UserData.UserName" />
            </el-form-item>
            <el-form-item label="用户密码">
                <el-input v-model="UserData.UserPwd" show-password />
            </el-form-item>
            <el-form-item label="角色">
                <el-checkbox-group v-model="UserData.Roles">
                    <el-checkbox v-for="item in RoleData" :value="item.Id">
                        {{ item.RoleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="是否启用">
                <el-switch v-model="UserData.IsUse" class="ml-2" inline-prompt
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用"
                    inactive-text="禁用" />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="UserData.CreateTime" type="datetime" placeholder="请选择创建时间"
                    format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s a" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="isSubmitting" @click="AddUserWay()" :disabled="isSubmitting">
                  <el-icon v-if="isSubmitting"><Loading /></el-icon>
                  <el-icon v-else><Check /></el-icon>
                  添加
                </el-button>
                <el-button @click="OpenUserAdd = false" :disabled="isSubmitting">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
            </el-form-item>
        </el-form>
        <!-- 用户编辑 -->
    </el-dialog>
    <!-- 用户编辑 -->
    <el-dialog v-model="OpenUserUpdate" title="用户编辑" width="500" align="center">
        <el-form :model="UserData" label-width="auto" style="max-width: 600px">
            <el-form-item label="用户名">
                <el-input v-model="UserData.UserName" />
            </el-form-item>
            <el-form-item label="用户密码">
                <el-input v-model="UserData.UserPwd" show-password />
            </el-form-item>
            <el-form-item label="角色">
                <el-checkbox-group v-model="UserData.Roles">
                    <el-checkbox v-for="item in RoleData" :value="item.Id">
                        {{ item.RoleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="是否启用">
                <el-switch v-model="UserData.IsUse" class="ml-2" inline-prompt
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用"
                    inactive-text="禁用" />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="UserData.CreateTime" type="datetime" placeholder="请选择创建时间"
                    format="YYYY/MM/DD HH:mm:ss" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="isSubmitting" @click="UpdateUserWay()" :disabled="isSubmitting">
                  <el-icon v-if="isSubmitting"><Loading /></el-icon>
                  <el-icon v-else><Check /></el-icon>
                  保存
                </el-button>
                <el-button @click="OpenUserUpdate = false" :disabled="isSubmitting">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 分页组件 -->
    <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: center;">
        <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
            :page-sizes="[2, 4, 6, 8,10]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount"
            :current-page-label="'当前页'" :page-sizes-label="'每页显示条数'" :prev-text="'上一页'" :next-text="'下一页'"
            :jumper-text="['前往', '页']" :disabled="isLoading" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElCard, ElInput, ElButton, ElTable, ElTableColumn, ElPagination, ElMessage, ElMessageBox, ElPopconfirm } from 'element-plus'
import { Search, Plus, Edit, Delete, Check, Close, Loading } from '@element-plus/icons-vue'
import httpaxios from '@/AxiosHelp'
import moment from 'moment'
httpaxios.defaults.baseURL = "http://localhost:5297"
onMounted(() => {
    GetUserData(); //获取用户数据
    GetRoles(); //获取角色数据
})
// 搜索关键词
const searchUsername = ref('')
// 分页数据
const page = reactive({
    pageindex: 1,
    pagesize: 4,
    totalcount: 0
})
//用户数据变量
const userData = ref([])
// 加载状态
const isLoading = ref(false)
// 提交状态
const isSubmitting = ref(false)
//#region   用户显示
//获取用户数据
const GetUserData = () => {
    isLoading.value = true
    httpaxios.get("api/Users/UserGet", {
        params: {
            pageindex: page.pageindex,
            pagesize: page.pagesize,
            UserName: searchUsername.value
        }
    }).then(res => {
        console.log(res.data);
        userData.value = res.data.PageData;
        page.totalcount = res.data.Totalcount;
    }).catch(error => {
        console.error('获取用户数据失败:', error)
        ElMessage.error('获取用户数据失败，请重试')
    }).finally(() => {
        isLoading.value = false
    })
}
//分页侦听器
watch(page, () => { GetUserData() }
)
//#endregion
//#region   用户删除  
// 处理添加用户点击事件
const handleAddUser = () => {
    OpenUserAdd.value = true
    UserData.UserName = ''
    UserData.UserPwd = ''
    UserData.Roles = []
    UserData.IsUse = true
}

// 处理删除用户
const handleDeleteUser = (Id: any) => {
    isLoading.value = true
    httpaxios.put("/api/Users/UserDel", { UserId: Id }).then(res => {
        console.log(res.data);
        if (res.data.Code == 200) {
            ElMessage.success(res.data.Message)
            //刷新页面
            GetUserData();
        }
        else {
            ElMessage.error(res.data.Message)
        }
    }).catch(error => {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败，请重试')
    }).finally(() => {
        isLoading.value = false
    })
}
//#endregion
//#region   用户添加    
const OpenUserAdd = ref(false);
const UserData = reactive({
    UserId: null,
    Roles: [],
    "UserName": "",
    "UserPwd": "",
    "CreateTime": "",
    "IsUse": true,
    "RoleIds": "",
    CheckedRoles: ""
})
const AddUserWay = () => {
    // 简单验证
    if (!UserData.UserName || !UserData.UserPwd) {
        ElMessage.warning('请填写用户名和密码')
        return
    }
    
    isSubmitting.value = true
    httpaxios.post("/api/Users/UserAdd", {
        "UserName": UserData.UserName,
        "UserPwd": UserData.UserPwd,
        "CreateTime": new Date(), // 存储当前时间戳
        "IsUse": true, //默认启用
        "RoleIds": UserData.Roles.toString()
    }).then(res => {
        console.log(res.data);
        if (res.data.Code == 200) {
            ElMessage.success(res.data.Message)
            //刷新页面
            GetUserData();
            OpenUserAdd.value = false
        }
        else {
            ElMessage.error(res.data.Message)
        }
    }).catch(error => {
        console.error('添加用户失败:', error)
        ElMessage.error('添加用户失败，请重试')
    }).finally(() => {
        isSubmitting.value = false
    })
}
//角色数据
const RoleData = ref([{
    "Id": null,
    "RoleName": "",
}])
const GetRoles = () => {
    httpaxios.get("/api/Roles/RoleGet", { params: {} }).then(res => {
        console.log(res.data);
        RoleData.value = res.data.PageData;
    })
}
//#endregion
//#region 用户编辑
const OpenUserUpdate = ref(false);

const GetoneUser = (row: any) => {
    if (isLoading.value) return
    
    //打开对话框
    OpenUserUpdate.value = true
    
    // 单角色数据反填
    UserData.UserId = row.Id
    UserData.UserName = row.UserName
    UserData.UserPwd = row.UserPwd
    UserData.IsUse = row.IsUse
    UserData.Roles = row.CheckedRoles ? row.CheckedRoles.split(",").map(Number) : []
    UserData.CreateTime = row.CreateTime
}
const UpdateUserWay = () => {
    // 简单验证
    if (!UserData.UserName || !UserData.UserPwd) {
        ElMessage.warning('请填写用户名和密码')
        return
    }
    
    isSubmitting.value = true
    httpaxios.put("/api/Users/UserUpdate", {
        Id: UserData.UserId,
        "UserName": UserData.UserName,
        "UserPwd": UserData.UserPwd,
        "CreateTime": new Date(), // 存储当前时间戳
        "IsUse": UserData.IsUse, // 使用表单中的启用状态
        "RoleIds": UserData.Roles.toString()
    }).then(res => {
        console.log(res.data);
        if (res.data.Code == 200) {
            ElMessage.success(res.data.Message)
            OpenUserUpdate.value = false
            //刷新页面
            GetUserData();
        }
        else {
            ElMessage.error(res.data.Message)
        }
    }).catch(error => {
        console.error('更新用户失败:', error)
        ElMessage.error('更新用户失败，请重试')
    }).finally(() => {
        isSubmitting.value = false
    })
}
//#endregion
</script>

<style scoped>
/* 页面容器样式 */
.user-list-container {
    margin: 20px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

/* 搜索和添加区域样式 */
.search-add-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

/* 分页容器样式 */
.pagination-container {
    margin-top: 20px;
}

/* 表格单元格内按钮样式优化 */
.el-table__row .el-button {
    margin-right: 8px;
    transition: all 0.3s ease;
}

/* 按钮悬停效果增强 */
.el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

/* 按钮禁用状态优化 */
.el-button:disabled {
    opacity: 0.6;
    transform: none;
    cursor: not-allowed;
}

/* 表格操作列样式调整 */
.el-table-column--fixed-right .cell {
    display: flex;
    justify-content: center;
    gap: 8px;
}

/* 对话框内表单样式优化 */
.el-dialog__body .el-form-item {
    margin-bottom: 16px;
}

/* 搜索框样式增强 */
.search-add-area .el-input {
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.search-add-area .el-input:focus-within {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .user-list-container {
        margin: 10px;
        padding: 15px;
    }
    
    .search-add-area {
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .search-add-area .el-input {
        width: 100% !important;
        margin-right: 0 !important;
    }
}
</style>